package ebcs.scan.controller.messageCtr;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;

import ebcs.database.bean.BsGroupInfor;
import ebcs.database.bean.BsProTeamInfor;
import ebcs.database.bean.BsUserInfor;
import ebcs.database.bean.TbMessage;
import ebcs.database.bean.TbMessageDetail;
import ebcs.database.bean.TbMessageInfor;
import ebcs.database.bean.TbTemplate;
import ebcs.database.service.MessageServiceImp;
import ebcs.scan.service.wechat.WeChatTemplPushService;
import ebcs.scan.service.wechat.bean.WechatTemplateList;
import jplat.core.trans.JAppBaseService;
import jplat.core.trans.JAppContext;
import jplat.error.exception.JSystemException;
import jplat.error.exception.JTransException;

/**
 * 推送消息管理
 * @author JMY
 *
 */
@Controller
public class MessageCtr extends JAppBaseService {
	
	@Autowired
    public MessageServiceImp messageService;
	
	@Autowired
    public WeChatTemplPushService weChatTemplPushService;

	/**
	 * 需求展示 
	 */
	@RequestMapping("/page/message/doShowMessage.do")
	public String doShowMessage( HttpServletRequest request,HttpServletResponse response ) throws JTransException, JSystemException{
		return "main/report/messageManage";
	}
	
	/**
	 * 推送消息列表查询
	 * @param request
	 * @param response
	 * @throws JTransException
	 * @throws JSystemException
	 */
    @RequestMapping("/page/message/searchMessageInfor.do")
    public void searchMessageInfor(HttpServletRequest request, HttpServletResponse response) throws JTransException, JSystemException {
        JAppContext context = serviceFactory.buildAppContextNoUser(request, response);//自动客户信息
        TbMessage message = context.obtainReqModel(TbMessage.class);
        List<TbMessageInfor> messgaeInforList = messageService.selectMessageInfor(message);
        context.buildAppResponse(messgaeInforList);
    }
    
    /**
     * 新增推送消息
     * @param request
     * @param response
     * @return
     * @throws JTransException
     * @throws JSystemException
     */
    @RequestMapping("/page/message/addMessageInfor.do")
    public String addMessageInfor(HttpServletRequest request, HttpServletResponse response, String sign, String messageId) throws JTransException, JSystemException {
    	List<TbTemplate> tempList = messageService.getTempList();	//获取模板列表
    	TbTemplate template = new TbTemplate();
    	String tempContent = "";
 		if("2".equals(sign)) { //编辑更新
 			TbMessage message = new TbMessage();
 			message.setMessageId(messageId);
 	        List<TbMessageInfor> messageInforList = messageService.selectMessageInfor(message);
 	        if (!CollectionUtils.isEmpty(messageInforList)) {
 	            request.setAttribute("message", messageInforList.get(0));
 	        }
 	        String templateId = messageInforList.get(0).getTemplateId();
 	        for(int i=0;i<tempList.size();i++) {
 	        	if((tempList.get(i).getTemplateId()).equals(templateId)) {
 	        		template = tempList.get(i);
 	        	}
 	        }
 	        tempContent = template.getContent();
 	        List<TbMessageDetail> messageData = messageService.selectMsgDetailAll(messageId);
 	        request.setAttribute("messageData", messageData);
 		}else if("1".equals(sign)) { //新增
 			tempContent = tempList.get(0).getContent();
 		}
 		// 获取模板data中的字段List
 		List<String> list = new ArrayList<String>();
		int start = 0;
		int startFlag = 0;
		int endFlag = 0;
		for (int i = 0; i < tempContent.length(); i++) {
			if (tempContent.charAt(i) == '{') {
				startFlag++;
				if (startFlag == endFlag + 1) {
					start = i;
				}
			} else if (tempContent.charAt(i) == '}') {
				endFlag++;
				if (endFlag == startFlag) {
					list.add(tempContent.substring(start + 1, i).replace(".DATA}", "").replace("{", ""));
				}
			}
		}
		request.setAttribute("template", list);		//返回模板内容
 		request.setAttribute("tempList", tempList);
 		request.setAttribute("sign", sign);
    	return "main/report/addMessage";
    }
    
    /**
         *删除推送消息
     * @param request
     * @param response
     * @throws JTransException
     * @throws JSystemException
     */
    @RequestMapping("/page/message/deleteMessage.do")
    public void deleteMessage(HttpServletRequest request, HttpServletResponse response) throws JTransException, JSystemException {
        JAppContext context = serviceFactory.buildAppContextNoUser(request, response);//自动客户信息
        TbMessage message = context.obtainReqModel(TbMessage.class);
        messageService.deleteMessage(message.getMessageId());
        Map rspModel = new HashMap();
        context.buildAppResponse(rspModel);
    }
    
    /**
     * 保存推送消息
     * @param request
     * @param response
     * @throws JTransException
     * @throws JSystemException
     */
    @RequestMapping("/page/message/saveMessage.do")
    public void saveMessage(HttpServletRequest request, HttpServletResponse response) throws JTransException, JSystemException {
        JAppContext context = serviceFactory.buildAppContextNoUser(request, response);//自动客户信息
        TbMessageInfor message = context.obtainReqModel(TbMessageInfor.class);
        if("1".equals(message.getSign())) {
        	String messageId = UUID.randomUUID().toString().replaceAll("-", "");
        	message.setMessageId(messageId);
        	messageService.addMessage(message);
        	
        	String messageData = message.getMessageData();
        	Gson gson = new Gson();
        	Map map = gson.fromJson(messageData, HashMap.class);
        	Iterator<String> iter = map.keySet().iterator();
        	while(iter.hasNext()){
        		String key=iter.next();
        		String value = (String) map.get(key);
        		TbMessageDetail tbMessageDetail = new TbMessageDetail();
        		tbMessageDetail.setMessageId(messageId);
        		//key = "set"+key.substring(0, 1).toUpperCase()+key.substring(1);
        		tbMessageDetail.setKey(key);
        		tbMessageDetail.setValue(value);
        		tbMessageDetail.setColor("#000000");
        		messageService.addMessageDetail(tbMessageDetail);
        	}
        }else if("2".equals(message.getSign())) {
        	messageService.deleteMessageDetail(message.getMessageId());// 先删除该message所有的messageDetail
        	
        	String messageData = message.getMessageData();
        	Gson gson = new Gson();
        	Map map = gson.fromJson(messageData, HashMap.class);
        	Iterator<String> iter = map.keySet().iterator();
        	while(iter.hasNext()){
        		String key=iter.next();
        		String value = (String) map.get(key);
        		TbMessageDetail tbMessageDetail = new TbMessageDetail();
        		tbMessageDetail.setMessageId(message.getMessageId());
        		//key = "set"+key.substring(0, 1).toUpperCase()+key.substring(1);
        		tbMessageDetail.setKey(key);
        		tbMessageDetail.setValue(value);
        		tbMessageDetail.setColor("#000000");
        		messageService.addMessageDetail(tbMessageDetail);// 再插入
        	}
        	
        	messageService.updateMessage(message);
        }
        request.setAttribute("message", message);
        request.setAttribute("sign", message.getSign());
        Map rspModel = new HashMap();
        context.buildAppResponse(rspModel);
    }
    
    /**
     * 改变模板AJAX
     * @param request
     * @param response
     * @param groupNo
     * @throws JTransException
     * @throws JSystemException
     */
    @RequestMapping("/page/message/{templateId}/changeTemplate.do")
    public void selectProTeamByGroupNo(HttpServletRequest request, HttpServletResponse response, @PathVariable String templateId) throws JTransException, JSystemException {
    	JAppContext context = serviceFactory.buildAppContextNoUser(request, response);//自动客户信息
        List<TbTemplate> tempList = messageService.getTempList();
        TbTemplate template = new TbTemplate();
        String tempContent = "";
        for(int i=0;i<tempList.size();i++) {
        	if((tempList.get(i).getTemplateId()).equals(templateId)) {
        		template = tempList.get(i);
        	}
        }
        tempContent = template.getContent();
        List<String> list = new ArrayList<String>();
		int start = 0;
		int startFlag = 0;
		int endFlag = 0;
		for (int i = 0; i < tempContent.length(); i++) {
			if (tempContent.charAt(i) == '{') {
				startFlag++;
				if (startFlag == endFlag + 1) {
					start = i;
				}
			} else if (tempContent.charAt(i) == '}') {
				endFlag++;
				if (endFlag == startFlag) {
					list.add(tempContent.substring(start + 1, i).replace(".DATA}", "").replace("{", ""));
				}
			}
		}
        Map rspModel = new HashMap();
        rspModel.put("tempList", list);
        context.buildAppResponse(rspModel);
    }
}
